package com.friend.service;

import com.friend.util.HttpContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p></p>
 *
 * @author jiuhua.xu
 * @version 1.0
 * @since JDK 1.8
 */
@Configuration
public class CustomPermissionEvaluator implements PermissionEvaluator {
    private static final Logger log = LoggerFactory.getLogger(CustomPermissionEvaluator.class);

    //普通的targetDomainObject判断
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        boolean hasPermission = false;
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        if (CollectionUtils.isEmpty(authorities)) {
            return false;
        }
        return this.doCheckAuth(request, authorities, authentication, targetDomainObject, permission);
    }

    //用于ACL的访问控制
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        log.error("-------------------------------------");
        return false;
    }

    private boolean doCheckAuth(HttpServletRequest request, Collection<? extends GrantedAuthority> authorities, Authentication auth, Object o, Object o1) {

        String requestURI = request.getRequestURI();

        String requestMethod = request.getMethod();

//        List<ResourceBO> resourceBoList= new ArrayList<>();
//
        for (GrantedAuthority grantedAuthority : authorities) {

            //拿到用户权限
            String authority = grantedAuthority.getAuthority();

            String authorityUrl = authority.substring(0,authority.lastIndexOf("_"));

            String method = authority.substring(authority.lastIndexOf("_")+1);
//
//            ResourceBO resourceBO = new ResourceBO();
//            resourceBO.setResourceUrl(authorityUrl);
//            resourceBO.setResourceMethod(mothed);
//            resourceBoList.add(resourceBO);
//        }
//        //判断是否有权限
//        ResourceBO resource = pathMatcher(requestURI, requestMethod, resourceBoList);
//
//        if(resource != null ){
//            return true ;
        }
        return false;
    }
}
